const express = require("express");
const app = express();
const port = 5000; // 此服务器端口
const cors = require("cors"); // 用来配置跨域
app.use(cors());
app.listen(port, () => {
    console.log("服务器已启动，链接: localhost:" + port);
});
// 将所有post传递转为对象
app.use(express.urlencoded({
    extended: true
}))
const userRouter = require("./router/user")
const commodityRouter = require("./router/Commodity")
const indentRouter = require('./router/indent')
const adminRouter = require('./router/admin')
const storeRouter = require('./router/offline_store')
const classifyRouter = require('./router/classify')
const hotRouter = require('./router/hot')
const newRouter = require('./router/new_arrival')
const logisticsRouter = require('./router/logistics')
const addressRouter = require('./router/addres')

app.use((req, res, next) => {
    if (req.url.indexOf('1.mp4') > -1) {
        res.setHeader('Cache-Control', 'public, max-age=3600'); // cache header
    }
    next();
});
// 将 post 的请求转对象
app.use(express.urlencoded({
    extended: true
}))

// 设定静态托管
app.use(express.static('public'));

// app.configure(function(){
//     app.use(function(req, res, next) {
//       var matchUrl = '/background.jpg';
//       if(req.url.substring(0, matchUrl.length) === matchUrl) {
//         res.setHeader("Cache-Control", "max-age=31556926");
//       }
//       return next();
//     });
//     app.use(express.static(path.join(application_root, "StaticPages")));
//     app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
//   });
app.get("/", (req, res) => {
    res.send("<h1>Mac 美妆</h1>");
});


app.use("/user", userRouter);
app.use("/commodity", commodityRouter);
app.use('/indent', indentRouter);
app.use('/admin', adminRouter);
app.use('/store', storeRouter);
app.use('/classify', classifyRouter);
app.use('/hot', hotRouter)
app.use('/new', newRouter);
app.use('/logistics', logisticsRouter)
app.use('/address', addressRouter)


app.use((err, req, res, next) => {
    console.log("出现了错误", err);
    res.send({ code: 500, msg: "服务器出现了错误" });
})


















// 在所有路由器的后边，添加错误处理的中间件，拦截所有的路由中出现的错误
app.use((err, req, res, next) => {
    // err 路由中传递过来的错误信息
    console.log(err)
    // 响应服务器端错误
    res.send({ code: 500, msg: '服务器端错误' })
})